package com.ckmod.zyr3x.tools.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.ckmod.zyr3x.tools.R;
import com.ckmod.zyr3x.tools.components.CSSConfig;
import com.ckmod.zyr3x.tools.components.CSystem;
import com.ckmod.zyr3x.tools.components.SeparatedListAdapter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import android.util.Log;

/**
 * Created by IntelliJ IDEA.
 * User: Олег Семенов
 * Date: 11.07.11
 * Time: 15:08
 * To change this template use File | Settings | File Templates.
 */
public class ASMode extends Activity {

    public final static String ITEM_TITLE = "title";
    public final static String ITEM_CAPTION = "caption";

    private String[] custome_settings;
    private String[] awake_settings_values;
    private String[] sleep_settings_values;
    private String[] governor_infos;
    private String[] governor_value;
    private String[]  governor_value_list;
    private String[] freq_values;
    private String[] freq_names;
    public static final String GOVERNORS_LIST_FILE = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors";
    private int  _currentPos;



    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        //Resources
        custome_settings =  getResources().getStringArray(R.array.custome_settings);
        awake_settings_values =  getResources().getStringArray(R.array.awake_settings_values);
        sleep_settings_values =  getResources().getStringArray(R.array.sleep_settings_values);
        governor_infos =  getResources().getStringArray(R.array.governor_infos);
        governor_value = CSystem.readOneLine(GOVERNORS_LIST_FILE).split(" ");
        governor_value_list = getResources().getStringArray(R.array.governor_value);
        freq_values =  getResources().getStringArray(R.array.freq_values);
        freq_names=  getResources().getStringArray(R.array.freq_names);

        init();
    }

    public void onBackPressed()
    {
        //CSSConfig.update();
        finish();
    }

    public void init()
    {
        SeparatedListAdapter adapter = new SeparatedListAdapter(this);

        adapter.addSection(getString(R.string.awake), simpleAdapter(custome_settings, awake_settings_values));
        adapter.addSection(getString(R.string.sleep), simpleAdapter(custome_settings, sleep_settings_values));

        ListView list = new ListView(this);
        list.setAdapter(adapter);
        list.setOnItemClickListener(onItemClickListener());
        list.setSelection(_currentPos);
        setContentView(list);

    }

    private AdapterView.OnItemClickListener onItemClickListener()
    {
      return new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                _currentPos = i;
                switch(i)
                {
                     case 1:
                        alertDialog(custome_settings[0],governor_value,awake_settings_values[0]);
                        break;
                     case 2:
                        alertDialog(custome_settings[1],getResources().getStringArray(R.array.freq_names),awake_settings_values[1]);
                        break;
                     case 3:
                        alertDialog(custome_settings[2],getResources().getStringArray(R.array.freq_names),awake_settings_values[2]);
                     break;
                      case 4:
                        alertDialog(custome_settings[3],getArrayValues(0,101,1,1),awake_settings_values[3]);
                      break;
                      case 5:
                          alertDialog(custome_settings[4],getArrayValues(0,6,0,25),awake_settings_values[4]);
                         break;
                      case 6:
                        alertDialog(custome_settings[5],getArrayValues(0,6,0,25),awake_settings_values[5]);
                      break;
                     case 8:
                        alertDialog(custome_settings[0],governor_value,sleep_settings_values[0]);
                        break;
                     case 9:
                        alertDialog(custome_settings[1],getResources().getStringArray(R.array.freq_names),sleep_settings_values[1]);
                        break;
                     case 10:
                        alertDialog(custome_settings[2],getResources().getStringArray(R.array.freq_names),sleep_settings_values[2]);
                     break;
                     case 11:
                        alertDialog(custome_settings[3],getArrayValues(0,101,1,1),sleep_settings_values[3]);
                     break;
                     case 12:
                        alertDialog(custome_settings[4],getArrayValues(0,6,0,25),sleep_settings_values[4]);
                        break;
                    case 13:
                        alertDialog(custome_settings[5],getArrayValues(0,6,0,25),sleep_settings_values[5]);
                     break;
                }
            }
        };
    }

    private void alertDialog(final String title,final CharSequence[] items,final String option)
    {
       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle(title);

       String val =  CSSConfig.getValue(option);
       int select = items.length - 1;

        if(option.indexOf("FREQ")!= -1)
        {
            String[] freq_values =  getResources().getStringArray(R.array.freq_values);

            for(int i = 0;i<freq_values.length;i++)
                if(freq_values[i].equals(val))
                    select = i;
        }
        else
        {
            for(int i = 0;i<items.length;i++)
                if(items[i].equals(val))
                    select = i;
        }


        builder.setSingleChoiceItems(items, select, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {

                    if(items[item].toString().equals(getString(R.string.custom)))
                    {
                       customDialog(title, option, option);
                       dialog.dismiss();

                    }
                    else
                    {
                           if(option.indexOf("FREQ")!= -1)
                              CSSConfig.setValue(option,getResources().getStringArray(R.array.freq_values)[item]);
                           else
                              CSSConfig.setValue(option,items[item].toString());
                        init();
                        dialog.dismiss();
                    }
                    init();

            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void customDialog(String title,final String name,final String option)
    {
        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        final EditText input = new EditText(this);
        String val =  CSSConfig.getValue(option);
        alert.setTitle(title);
        alert.setView(input);
        input.setText(val);
        input.setInputType(2);
        alert.setPositiveButton(getString(R.string.save), new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                      String value = input.getText().toString().trim();
                      CSSConfig.setValue(option,value);
                      init();
                      dialog.cancel();
                  }
              });

        alert.setNegativeButton(getString(R.string.back),
                  new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int whichButton) {
                          dialog.cancel();
                      }
                  });
        alert.show();


    }

    private SimpleAdapter simpleAdapter(String[] names, String[] info)
    {
        ArrayList<HashMap<String,String>> listData =  new ArrayList<HashMap<String,String>>();
        Object[] objInfo =  this.getCustomeInfo(info);

        SimpleAdapter simpleAdapter = new SimpleAdapter(this,listData,
                                R.layout.list_complex_menu,
                                new String[] {ITEM_TITLE, ITEM_CAPTION },
                                new int[] {R.id.list_complex_title, R.id.list_complex_caption,});

        for (int i = 0; i< names.length; i++)
        {
                    HashMap<String,String> temp = new HashMap<String,String>();
                    temp.put(ITEM_TITLE, names[i]);
                    temp.put(ITEM_CAPTION, objInfo[i].toString());
                    listData.add(temp);
        }
        simpleAdapter.notifyDataSetChanged();
        return simpleAdapter;
    }

    private Object[] getCustomeInfo(String[] info)
    {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i< info.length; i++)
        {
            switch(i)
            {
                case 0:
                    boolean set_info = false;
                    for (int j = 0; j< governor_value_list.length; j++)
                       if(governor_value_list[j].equals(CSSConfig.getValue(info[i])) )
                       {
                           list.add(governor_infos[j]);
                           set_info = true;
                       }
                       if(set_info==false)
                           list.add(CSSConfig.getValue(info[i]) + getString(R.string.no_description));
                break;
                default:
                    if(info[i].indexOf("FREQ")!= -1)
                    {
                       for (int j = 0; j< freq_values.length; j++)
                            if(freq_values[j].equals(CSSConfig.getValue(info[i])))
                                 list.add(getString(R.string.current_value)+freq_names[j]);
                    }
                    else
                        list.add(getString(R.string.current_value)+CSSConfig.getValue(info[i]));
                break;
            }
        }

        return list.toArray();
    }

    private CharSequence[] getArrayValues(int start, int count,int begin_step, int step)
    {
          CharSequence[] values = new CharSequence[count];
               for(int j=start,k=begin_step;j<values.length;j++,k+=step)
                   values[j] = (CharSequence)String.valueOf(k);

          values[count-1] = getString(R.string.custom);
          return values;
    }
}

